package com.zykj.thread.traditional.synchronizeddemo;

/**
 * @author zhoulj(周利军) [1217102780@qq.com]
 * @Module ID:   <(模块)类编号，可以引用系统设计中的类编号>
 * @Comments: <对此类的描述，可以引用系统设计中的描述>
 * @JDK version used:      <JDK1.8> 17
 * @since 2019/1/14-14:17
 */
public class SynchronizedDemo {

    public static void main(String[] args) {
        final OutPut outPut = new OutPut();
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    outPut.output("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
                }
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
//                    outPut.output("cccccccccccccccccccccccccccccccccccccccccccccc");
                    outPut.output2("cccccccccccccccccccccccccccccccccccccccccccccc");
                }
            }
        }).start();


    }

    static class OutPut {
        public void output(String str) {
            synchronized (this) {
                for (int i = 0; i < str.length() ; i++) {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.print(str.charAt(i));
                }
                System.out.println();
            }

        }

        //TODO 这里方法上用  synchronized和 使用synchronized 代码块 使用的是同一个 锁对象
        public synchronized void output2(String str) {
                for (int i = 0; i < str.length() ; i++) {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.print(str.charAt(i));
                }
                System.out.println();

        }
    }
}
